// /*
//  * @Author: WanYiMing
//  * @Date:2024-07-25-18:17
//  * @Description:
//  */

using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.Serialization;

namespace Code.Monster
{
    public class MonsterLeaderController : MonoBehaviour
    {
        //下属集合
        private List<MonsterController> _subMonsters;

        //下属数量
        public int subSize = 25;

        //集结完毕
        private bool _assemblyOver;

        //集结范围
        public float assemblyRadius=5;
        public float moveSpeed = 2f;
        private Vector3 _targetPosition;
        private SpaceLine _spaceLine;
        
        //随机点
        private Transform _assemblyRandomPosition;

    
        
        private void Start()
        {
            _assemblyOver = false;
            _subMonsters = new List<MonsterController>();
            _spaceLine = this.AddComponent<SpaceLine>();
            _spaceLine.Draw(assemblyRadius);
        }


        private void Update()
        {
            if (_assemblyOver && subSize == _subMonsters.Count)
            {
                AttackTarget();
            }
            else
            {
                AssemblyMonster();
            }
        }


        private void AssemblyMonster()
        {
            RandomMove();

            FindMonster();

            if (subSize <= _subMonsters.Count)
            {
                _assemblyOver = true;
            }
        }

        private void FindMonster()
        {
            Collider2D[] colliders = Physics2D.OverlapCircleAll(transform.position, assemblyRadius);
            foreach (Collider2D collider in colliders)
            {
                Debug.Log("Object in range: " + collider.gameObject.name);
                MonsterController monsterController = collider.gameObject.GetComponent<MonsterController>();
                if (monsterController is not null&&monsterController.IsAssembly(this))
                {
                    _subMonsters.Add(monsterController);   
                }

            }
        }

        private void RandomMove()
        {
            if (Vector3.Distance(transform.position, _targetPosition) <= .1f)
            {
                float randomAngle = Random.Range(0f, 2f * Mathf.PI);
                float xOffset = assemblyRadius * Mathf.Cos(randomAngle);
                float yOffset = assemblyRadius * Mathf.Sin(randomAngle);
                _targetPosition = new Vector2(transform.position.x + xOffset, transform.position.y + yOffset);
            }

            transform.position = Vector3.MoveTowards(transform.position, _targetPosition, moveSpeed * Time.deltaTime);
        }


        private void AttackTarget()
        {
        }
    }
}